<template>
	<view class="login-wrap">
		<view class="login-back" @tap="back"><text class="iconfont icon-xiangyoujiantou"></text></view>
		<view class="login-step login-step-first" :style="{ height: windowHeight + 'px' }" v-if="step === 'first'">
			<view class="login-step-first-part">
				<image class="login-app-logo" src="/static/logo/logo.jpg"></image>
				<view class="login-app-name">元尊商城</view>
			</view>
			<view class="login-step-first-part">
				<view class="login-btn login-btn-small" @tap="enter">手机号登录</view>
				<text class="login-tips">未注册用户将自动注册</text>
				<view class="login-oauth">
					<template v-if="loginType == 'wechat' || loginType == 'wxapp'">
						<view class="login-oauth-text">— 快速登录 —</view>
						<view class="login-oauth-list">
							<view v-if="loginType == 'wechat'" @tap="redirectWechatAuth" class="login-oauth-icon"><image class="login-oauth-icon-image" src="/static/auth/weixin.png" mode="aspectFill"></image></view>

							<view v-if="loginType == 'wxapp'" class="login-oauth-icon">
								<button openType="getUserInfo" class="oauth-buttom" form-type="submit" @getuserinfo="mpGetUserInfoToOauth"><image class="login-oauth-icon-image" src="/static/auth/wxapp.png" mode="aspectFill"></image></button>
							</view>
						</view>
					</template>
				</view>
			</view>
		</view>
		<view class="login-step" v-if="step === 'second'">
			<view class="login-step-title">登录/注册</view>
			<view class="login-step-desc" v-if="authId">绑定商城账号，享受快捷登录</view>
			<view class="login-step-form">
				<view class="login-input"><input v-model="phone" type="number" class="login-input-area" placeholder-class="login-input-area-placeholder" placeholder="手机号/账号" /></view>
				<template v-if="phoneExist == 1">
					<view class="login-input"><input v-model="passwd" password="password" class="login-input-area" placeholder-class="login-input-area-placeholder" placeholder="密码" /></view>
				</template>
				<template v-if="phoneExist == 0">
					<view class="login-input">
						<input v-model="identifyCode" class="login-input-area" placeholder-class="login-input-area-placeholder" placeholder="验证码" />
						<view class="login-get-code" :style="{ color: getCodeBtnColor }" @tap="getCode">{{ getCodeText }}</view>
					</view>
					<view class="login-input"><input v-model="passwd" password="password" class="login-input-area" placeholder-class="login-input-area-placeholder" placeholder="密码" /></view>
					<view class="login-input">
						<input v-model="nickName" class="login-input-area" placeholder-class="login-input-area-placeholder" placeholder="昵称" />
						<view class="login-get-name" @tap.stop="getNickName">随机昵称</view>
					</view>
					<view class="login-input"><input :disabled="!!options.referee_id" v-model="referee_id" class="login-input-area" placeholder-class="login-input-area-placeholder" placeholder="邀请码" /></view>
				</template>
			</view>
			<view v-if="phoneExist == -1" class="login-btn" :class="{ 'login-btn-disable': !phoneValid }" @tap="next">下一步</view>
			<!-- #ifdef MP -->
			<button v-if="phoneExist == 1" openType="getUserInfo" @getuserinfo="mpGetUserInfoToLogin" class="login-btn" :class="{ 'login-btn-disable': !phoneValid || passwd.length < 6 }"><view>登录</view></button>
			<!-- #endif -->
			<!-- #ifndef MP -->
			<view v-if="phoneExist == 1" class="login-btn" :class="{ 'login-btn-disable': !phoneValid || passwd.length < 6 }" @tap="login">登录</view>
			<!-- #endif -->
			<view v-if="phoneExist == 0" class="login-btn" :class="{ 'login-btn-disable': !phoneValid || passwd.length < 6 }" @tap="register">注册</view>
			<view class="reset-password"><text @tap="toResetPassword">忘记密码？</text></view>
		</view>
	</view>
</template>

<script>
import Route from '@/utils/Route.js';
import Tools from '@/utils/Tools.js';
export default {
	data() {
		return {
			windowHeight: null,
			step: 'first',
			phone: '',
			phoneExist: -1,
			phoneValid: false,
			passwd: '',
			authId: '',
			loginType: 'h5',
			identifyCode: '',
			nickName: '',
			referee_id: '',
			getCodeText: '获取验证码',
			getCodeBtnColor: '#d10000',
			getCodeisWaiting: false,
			timer: null,
			options: {}
		};
	},
	onLoad(options) {
		// Tools.redirectToCurrentPage()
		this.options = options || {};

		if (options.next == 1) {
			this.step = 'second';
		}
		if (options.authId) {
			this.authId = options.authId;
		}
		this.getSystemInfo();
		//APP显示第三方登录
		// #ifdef APP-PLUS
		this.isShowOauth = true;
		this.loginType = 'app';
		// #endif
		// #ifdef MP-WEIXIN
		this.loginType = 'wxapp';
		// #endif
		// #ifdef H5
		if (Tools.isWechat()) {
			this.loginType = 'wechat';
			// if (this.code && !this.authed) {
			// 	this.wechath5Login();
			// }
		}
		// #endif
	},
	onShow() {
		this.referee_id = Tools.getSuperiorId() || '';
		this.$post(this.$api.checkRefereeCode, { referee_id: this.referee_id }, res => {
			if (res.data.status != 1) {
				this.referee_id = '';
			}
		});
	},
	watch: {
		phone() {
			this.phoneExist = -1;
			this.phoneValid = this.validPhone();
		}
	},
	methods: {
		back() {
			if (this.step == 'second') {
				this.step = 'first';
			} else {
				Route.navigateBack();
			}
		},
		enter() {
			this.step = 'second';
		},
		//跳转微信授权页面
		redirectWechatAuth() {
			const state = { type: 'login', referee_id: this.referee_id };
			uni.setStorageSync('oauth', state);
			location.href = this.$link(this.$api.getWechatCode, { url: Tools.getSite() + '/pages/oauth/wechat', state: JSON.stringify(state) });
		},
		//跳转微信授权页面
		redirectWechatGetAuthId() {
			const state = { type: 'home' };
			uni.setStorageSync('oauth', state);
			location.href = this.$link(this.$api.getWechatCode, { url: Tools.getSite() + '/pages/oauth/wechat', state: JSON.stringify(state) });
		},
		mpGetUserInfoToOauth(e) {
			let detail = e.detail;
			if (detail.errMsg === 'getUserInfo:ok') {
				delete detail.errMsg;
				uni.setStorageSync('appUserDetail', detail);
				Route.navigateTo({
					url: '/pages/oauth/mp?type=login'
				});
			}
		},
		mpGetUserInfoToLogin(e) {
			let detail = e.detail;
			if (detail.errMsg === 'getUserInfo:ok') {
				delete detail.errMsg;
				uni.setStorageSync('appUserDetail', detail);
				this.login();
			}
		},
		redirectMPGetAuthId() {
			Route.redirectTo({
				url: '/pages/oauth/mp?type=home'
			});
		},
		getCode() {
			uni.hideKeyboard();
			if (this.getCodeisWaiting) {
				return;
			}
			if (!this.validPhone()) {
				Tools.showError('请填写正确手机号码');
				return false;
			}
			this.getCodeText = '发送中...';
			this.getCodeisWaiting = true;
			this.getCodeBtnColor = 'rgba(209, 0, 0,0.5)';
			//示例用定时器模拟请求效果
			this.$get(
				this.$api.sendCode,
				{ phone: this.phone },
				res => {
					if (res.code === 1) {
						uni.showToast({ title: '验证码已发送', icon: 'none' });
						this.setTimer();
					} else {
						uni.showToast({ title: res.message, icon: 'none' });
					}
				},
				() => {
					this.getCodeText = '获取验证码';
					this.getCodeBtnColor = '#d10000';
					this.getCodeisWaiting = false;
				}
			);
		},
		setTimer() {
			let holdTime = 60;
			this.getCodeText = '重新获取(60)';
			this.timer = setInterval(() => {
				if (holdTime <= 0) {
					this.getCodeisWaiting = false;
					this.getCodeBtnColor = '#d10000';
					this.getCodeText = '获取验证码';
					clearInterval(this.timer);
					return;
				}
				this.getCodeText = '重新获取(' + holdTime + ')';
				holdTime--;
			}, 1000);
		},
		validPhone() {
			if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(this.phone)) {
				return false;
			}
			return true;
		},
		getSystemInfo() {
			const systemInfo = uni.getSystemInfoSync();
			this.windowHeight = systemInfo.windowHeight;
		},
		next() {
			if (!this.validPhone()) {
				Tools.showError('请填写正确手机号码');
				return false;
			}
			this.$get(this.$api.checkPhoneAccount, { phone: this.phone }, res => {
				this.phoneExist = res.data.account;
			});
		},
		getNickName() {
			this.$get(this.$api.getNickName, {}, res => {
				this.nickName = res.data.nick_name;
			});
		},
		getUserInfo(token) {
			uni.showLoading({
				title: '已登陆，获取用户信息...'
			});
			Tools.getUserInfo(
				() => {
					if (this.authId) {
						Tools.redirectToCurrentPage();
					} else {
						switch (this.loginType) {
							case 'wechat':
								this.redirectWechatGetAuthId();
								break;
							case 'wxapp':
								this.redirectMPGetAuthId();
								break;
							default:
								// Route.reLaunch();
								Tools.redirectToCurrentPage();
								break;
						}
					}
				},
				null,
				() => {
					uni.hideLoading();
				}
			);
		},
		login() {
			uni.hideKeyboard();
			//验证手机号码
			if (!this.validPhone()) {
				Tools.showError('请填写正确手机号码');
				return false;
			}
			if (this.passwd.length < 6) {
				Tools.showError('登录密码不能小于6位');
				return false;
			}
			const CryptoJS = require('crypto-js');
			const password = CryptoJS.AES.encrypt(CryptoJS.MD5(this.passwd).toString(), CryptoJS.enc.Utf8.parse('sgg45747ss223411'), { mode: CryptoJS.mode.ECB }).toString();
			uni.showLoading({
				title: '登录中...'
			});
			this.$post(
				this.$api.loginForPassword,
				{ phone: this.phone, password, login_type: this.loginType, id: this.authId },
				res => {
					if (res.code === 1) {
						uni.setStorageSync('token', res.data.token);
						this.getUserInfo();
					} else {
						Tools.showError(res.msg);
					}
				},
				null,
				() => {
					uni.hideLoading();
				}
			);
		},
		toResetPassword() {
			Route.navigateTo({
				url: '/pages/login/reset-password'
			});
		},
		register() {
			uni.hideKeyboard();
			//验证手机号码
			if (!this.validPhone()) {
				Tools.showError('请填写正确手机号码');
				return false;
			}
			if (this.passwd.length < 6 || this.passwd.length > 20) {
				uni.showToast({ title: '密码大于6位小于20位', icon: 'none' });
				return false;
			}
			uni.showLoading({
				title: '注册中...'
			});
			const CryptoJS = require('crypto-js');
			const password = CryptoJS.AES.encrypt(CryptoJS.MD5(this.passwd).toString(), CryptoJS.enc.Utf8.parse('sgg45747ss223411'), { mode: CryptoJS.mode.ECB }).toString();

			this.$post(
				this.$api.regForPhone,
				{ phone: this.phone, password, nickName: this.nickName, identifyCode: this.identifyCode, referee_id: this.referee_id, login_type: this.loginType, id: this.authId },
				res => {
					if (res.code === 1) {
						uni.showLoading({
							title: '正在创建用户档案...'
						});
						uni.setStorageSync('token', res.data.token);
						this.getUserInfo();
					} else {
						Tools.showError(res.msg);
					}
				},
				null,
				() => {
					uni.hideLoading();
				}
			);
		}
	}
};
</script>

<style>
page {
	background: #fff;
}
.login-wrap {
	background: #fff;
	overflow: hidden;
}
.login-step-first-part {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
}
.login-step {
	padding: calc(var(--status-bar-height) + 88rpx) 30rpx 0;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	overflow: hidden;
	box-sizing: border-box;
}
.login-step-first {
	padding-bottom: 40rpx;
	justify-content: space-between;
}
.login-app-logo {
	margin-top: 100rpx;
	height: 120rpx;
	width: 120rpx;
}
.login-app-name {
	font-family: hanyi;
	font-size: 40rpx;
	color: #363636;
	margin-top: 30rpx;
}
.login-btn {
	height: 80rpx;
	width: 100%;
	background: #d10000;
	color: #fff;
	display: flex;
	justify-content: center;
	align-items: center;
	font-size: 28rpx;
	border-radius: 12rpx;
}
.login-btn-disable {
	opacity: 0.5;
}
.login-btn-small {
	width: 400rpx;
}
.login-tips {
	font-size: 24rpx;
	line-height: 60rpx;
	color: #999;
}
.login-oauth {
	padding: 30rpx 0 20rpx;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
}
.login-oauth-text {
	height: 60rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	color: rgba(108, 108, 108, 0.8);
	font-size: 28rpx;
}
.login-oauth-list {
	width: 100%;
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 20rpx 0;
}
.login-oauth-icon {
	margin: 0 20upx;
}
.login-oauth-icon-image {
	width: 80rpx;
	height: 80rpx;
}
.login-step-title {
	font-size: 40rpx;
	width: 100%;
}
.login-step-desc {
	font-size: 28rpx;
	width: 100%;
	color: #999;
	line-height: 50rpx;
}
.login-step-form {
	margin-top: 40rpx;
	margin-bottom: 60rpx;
	width: 100%;
	display: flex;
	justify-content: center;
	align-items: center;
	flex-direction: column;
}
.login-input {
	display: flex;
	justify-content: space-between;
	align-items: center;
	height: 80rpx;
	width: 100%;
	border-bottom: 1rpx solid #f3a5a5;
	margin-bottom: 60rpx;
}
.login-input:nth-last-child(1) {
	margin-bottom: 20rpx;
}
.login-input-area {
	height: 80rpx;
	flex: 1;
}
.login-input-area-placeholder {
	font-size: 26rpx;
	color: #999999;
}
.login-get-code,
.login-get-name {
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 28rpx;
	padding: 0 20rpx;
}
.login-get-name {
	color: #d10000;
}
.login-back {
}
.login-back {
	width: 50rpx;
	height: 80rpx;
	position: absolute;
	top: calc(var(--status-bar-height) + 4rpx);
	display: flex;
	justify-content: center;
	align-items: center;
	transform: rotate(180deg);
	font-size: 40rpx;
	left: 20rpx;
}
.reset-password {
	width: 100%;
	line-height: 60rpx;
	font-size: 25rpx;
	margin-top: 10rpx;
	color: #aaa;
}
.oauth-buttom {
	background: none;
}
</style>
